package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.Page;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("dish")
public class DishController {
    //依赖注入
    @Autowired
    private DishService dishService;
    @Autowired
    private HttpSession session;

    //添加菜品信息
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        //获取登录的id
        Long id = (Long) session.getAttribute("employee");
        //完善信息
        dishDto.setCreateUser(id);
        dishDto.setUpdateUser(id);
        //调用业务方法
        dishService.save(dishDto);
        return R.success("添加成功");
    }

    //连表分页查询
    @GetMapping("/page")
    public R<Page<DishDto>> findAll2(Integer page, Integer pageSize, String name) {
        //调用分页数据查询方法
        //1.分表查询
        Page<DishDto> dishDtoPage = dishService.findAll(page, pageSize, name);
        //2.连表查询
        //Page<DishDto> dishDtoPage = dishService.findAll2(page, pageSize, name);

        return R.success(dishDtoPage);
    }

    //修改菜品信息先根据id进行数据回显
    @GetMapping("/{id}")
    public R<DishDto> findById(@PathVariable Long id) {
        //调用业务层获取数据
        DishDto dishDto = dishService.findById(id);
        return R.success(dishDto);
    }

    //id获取查询菜品列表数据
    @RequestMapping("/list")
    public R<List<DishDto>> findByCategoryId(Long categoryId ,Integer status) {
        //调用用方法
        //List<Dish> dishList = dishService.findByCategoryId(categoryId);
        return R.success(dishService.findByCategoryIdAndStatus(categoryId, status));
    }
    //修改菜品信息
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        //获取登录id
        Long id = (Long) session.getAttribute("employee");
        //写进菜品信息的修改人信息栏
        dishDto.setUpdateUser(id);
        //调用业务层方法进行菜品信息修改
        dishService.update(dishDto);
        return R.success("修改成功");
    }
}
